const router = require("express").Router();
const {Ajax, enu} = require("../utils/Ajax");
const {mysql, SqlQuery} = require('../utils/mysql');
const {JsonToken} = require('../utils/TokenJwt');
const logging = require("../utils/log");
const GetCode = require('../controller/Captcha').GetCode

/**
 * 登录
 * @param user,password
 * @return 登陆状态
 * @return 个人信息
 */
router.post('/login', async (req, res) => {
    try {
        const {user, password, code} = req.body
        if (code !== GetCode().code) {
            res.send(Ajax(enu().code.login.fail, enu().login.CodeError, new Date()))
            return;
        }
        if (!user && !password) {
            res.send(Ajax(enu().code.login.fail, enu().login.null, null))
        } else {
            const [state] = await mysql.query(SqlQuery().login, [user, password])
            if (state.length > 0) {
                logging('info',`${user}登陆成功!`)
                await res.send(Ajax(enu().code.login.success, enu().login.success, {
                    token: JsonToken(state[0].id, state[0].name, state[0].role, new Date().getTime()),
                    UserInfo: state[0]
                }))
            } else {
                await logging('error', `${user}登陆失败!`)
                await res.send(Ajax(enu().code.login.fail, `${user}  ${enu().login.fail}`, new Date()))
            }
        }
    } catch (err) {
        res.send(err)
    }
})


module.exports = router